package com.example.onlineeducation.viewmodel


import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.example.onlineeducation.repository.UserRepository
import com.example.onlineeducation.base.BaseViewModel
import com.example.onlineeducation.data.json.LoginJson
import com.yc.jetpacklib.net.YcResult
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.collectLatest


/**
 * Creator: yc
 * Date: 2021/6/15 18:03
 * UseDes:
 */
class LoginVM : BaseViewModel() {

    private val mUserRepository: UserRepository by lazy { UserRepository(mApiService) }


    private val _mLogin = MutableLiveData<YcResult<LoginJson>>()
    val mLogin: LiveData<YcResult<LoginJson>> = _mLogin

    fun login(phoneNum: String, verifyCode: String) = ycLaunch {
        mUserRepository.login(phoneNum, verifyCode).ycHasLoading().collectLatest { result ->
            _mLogin.postValue(result)
        }
    }

    private val _mSendVerifyCode = MutableLiveData<YcResult<String>>()
    val mSendVerifyCode: LiveData<YcResult<String>> = _mSendVerifyCode

    private val _mSendVerifyCodeResult = MutableLiveData<Any?>()
    val mSendVerifyCodeResult: LiveData<Any?> = _mSendVerifyCodeResult

    private var mVerifyCodeSendJob: Job? = null
//    private val mVerifyCodeSendLoop: YcLoopBase2 by lazy {
//        YcLoopBase2().apply {
//            mPeriodTime = 1000
//            mBlock = {
//                println("${System.currentTimeMillis()/100}----")
//                _mSendVerifyCodeResult.postValue(null)
//            }
//        }
//    }
//    private val mVerifyCodeSendLoop: YcLoopBase2 by YcLoopBase2.init(viewModelScope, 2000) {
//        mTime--
//        if (mTime < 0) {
//            mViewBinding.tvGetVerifyCode.apply {
//                text = "获取验证码"
//                isEnabled = true
//                mVerifyCodeSendLoop.finish()
//            }
//        } else {
//            mViewBinding.tvGetVerifyCode.apply {
//                text = "${mTime}秒"
//                isEnabled = false
//            }
//        }
//    }
    /**
     * 发送短信验证码+
     * @param phoneNum String 手机号
     */
    fun sendVerifyCode(phoneNum: String) {
        mVerifyCodeSendJob?.cancel()
        mVerifyCodeSendJob = ycLaunch {
//            mVerifyCodeSendLoop.start()
            mUserRepository.sendVerifyCode(phoneNum).ycHasLoading(delayTime = 0).collectLatest { result ->
                _mSendVerifyCode.postValue(result)
            }
        }
    }

    fun cancelVerifyCode() {
        mVerifyCodeSendJob?.cancel()
    }
}


